//
//  meInfoController.swift
//  专业课
//
//  Created by 梓简王 on 2017/8/24.
//  Copyright © 2017年 梓简王. All rights reserved.
//

import Foundation
import TextFieldEffects
import QorumLogs
import Alamofire

class meInfoController: UIViewController,headerViewDelegate,UITextFieldDelegate,PickerViewDelegete {
    var userTelInsertLable: AkiraTextField!
    var userNameInsertLable: AkiraTextField!
    var userTargetProfsInsertLable: AkiraTextField!
    var userFromSchoolInsertLable: AkiraTextField!
    var picker:DatePickerView?
    var clickSchoolFlag:Int = 0
    
    var header:headerView?
    override func viewDidLoad() {
        super.viewDidLoad()
        initUI()
    }
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
    }
    func initUI(){
        userTelInsertLable = AkiraTextField(frame: CGRect(x: 0, y: 0, width: commonVariable.SYSTEM_WIDTH/3*2, height: 50))
        userTelInsertLable.placeholder = "点击修改用户手机号码"
        userTelInsertLable.enabled = false
        userTelInsertLable.text = "\((commonVariable.LOCAL_USER!.userTel)!)"
        userTelInsertLable.center = CGPoint(x: commonVariable.SYSTEM_WIDTH/2, y: 95)
        userTelInsertLable.textAlignment = .Center
        
        userNameInsertLable = AkiraTextField(frame: CGRect(x: 0, y: 0, width: commonVariable.SYSTEM_WIDTH/3*2, height: 50))
        userNameInsertLable.placeholder = "点击修改您的昵称"
        userNameInsertLable.enabled = true
        userNameInsertLable.delegate = self
        userNameInsertLable.text = "\((commonVariable.LOCAL_USER?.userName)!)"
        userNameInsertLable.center = CGPoint(x: commonVariable.SYSTEM_WIDTH/2, y: 195)
        userNameInsertLable.textAlignment = .Center
        
        userTargetProfsInsertLable = AkiraTextField(frame: CGRect(x: 0, y: 0, width: commonVariable.SYSTEM_WIDTH/3*2, height: 50))
        userTargetProfsInsertLable.placeholder = "点击修改您的出生年月"
        userTargetProfsInsertLable.enabled = true
        userTargetProfsInsertLable.text = "\((commonVariable.LOCAL_USER?.userBirth)!)"
        userTargetProfsInsertLable.center = CGPoint(x: commonVariable.SYSTEM_WIDTH/2, y: 245)
        userTargetProfsInsertLable.delegate = self
        userTargetProfsInsertLable.textAlignment = .Center
        
        userFromSchoolInsertLable = AkiraTextField(frame: CGRect(x: 0, y: 0, width: commonVariable.SYSTEM_WIDTH/3*2, height: 50))
        userFromSchoolInsertLable.placeholder = "点击修改您的地址"
        userFromSchoolInsertLable.enabled = true
        userFromSchoolInsertLable.text = "\((commonVariable.LOCAL_USER?.userAddress)!)"
        userFromSchoolInsertLable.center = CGPoint(x: commonVariable.SYSTEM_WIDTH/2, y: 295)
        userFromSchoolInsertLable.delegate = self
        userFromSchoolInsertLable.textAlignment = .Center
        
        
        header = headerView(frame: commonVariable.HEADERPOSITION, leftBtnString: "< 返回", title: "\((commonVariable.LOCAL_USER?.userName!)!)", rightBtnString: "修改")
        header?.delegate = self
        
        self.view.backgroundColor = commonVariable.BACKGROUNDCOLOR
        self.view.addSubview(self.header!)
        self.view.addSubview(self.userTelInsertLable!)
        self.view.addSubview(self.userNameInsertLable!)
        self.view.addSubview(self.userTargetProfsInsertLable!)
        self.view.addSubview(self.userFromSchoolInsertLable!)
        self.view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: "handleTapBlank:"))
    }
    func clickLeftBtn() {
        self.dismissViewControllerAnimated(true) { () -> Void in
            
        }
    }
    func clickRightBtn() {
        //判断姓名是否符合规则
        if self.userNameInsertLable.text != ""{
            var length = 0
            for char in self.userNameInsertLable.text!.characters {
                // 判断是否中文，是中文+2 ，不是+1
                length += "\(char)".lengthOfBytesUsingEncoding(NSUTF8StringEncoding) == 3 ? 2 : 1
            }
            if length < 6 {
                SweetAlert().showAlert("用户名必须大于三个中文字符或6个英文字符")
                self.userNameInsertLable.text = ""
                self.userNameInsertLable.resignFirstResponder()
            }else if length > 16 {
                SweetAlert().showAlert("用户名不能大于8个中文字符或16个英文字符")
                self.userNameInsertLable.text = ""
                self.userNameInsertLable.resignFirstResponder()
            }
            return
        }
        //上传用户修改
        let tempUser = commonVariable.LOCAL_USER
        //防止传参为0
        if(commonVariable.LOCAL_USER?.commonAccountID == "0"){
            tempUser?.commonAccountID = ""
        }
        if(commonVariable.LOCAL_USER?.loverAccountID == "0"){
            tempUser?.loverAccountID = ""
        }
        tempUser?.userAddress = userFromSchoolInsertLable.text!
        tempUser?.userBirth = userTargetProfsInsertLable.text!
        tempUser?.userName = userNameInsertLable.text!
        let body = commonVariable.LOCAL_USER?.toDict() as! [String:String]
        
        self.view.userInteractionEnabled = false
        commonVariable.LOADING_PACMAN.center = commonVariable.WINDOWSCENTER
        self.view.addSubview(commonVariable.LOADING_PACMAN)
        commonVariable.LOADING_PACMAN.startAnimation()
        
        Alamofire.request(.POST, commonVariable.EDITUSERINFO,parameters:body,headers:nil).responseJSON() {
            response in
            self.view.userInteractionEnabled = true
            commonVariable.LOADING_PACMAN.stopAnimation()
            commonVariable.LOADING_PACMAN.removeFromSuperview()
            
            guard let JSONDIC = response.result.value else {
                QL4(response.result.error)
                switch response.result.error!.code {
                case -1009 :
                    SweetAlert().showAlert("对不起", subTitle: "请检查您的网络配置", style: AlertStyle.Error)
                case 3840:
                    SweetAlert().showAlert("对不起", subTitle: "服务出现故障，请联系管理员", style: AlertStyle.Error)
                case -1001 :
                    
                    SweetAlert().showAlert("对不起", subTitle: "上传信息超时", style: AlertStyle.Error)
                default:
                    SweetAlert().showAlert("对不起", subTitle: "请检查您的网络配置", style: AlertStyle.Error)
                }
                return }
            QL2(JSONDIC)
            let resultDict = JSONDIC as? NSDictionary
            let jsonObj = JSON(JSONDIC)
            let errorCode = jsonObj["errorcode"].intValue
            let errorMsg = jsonObj["message"].stringValue
            QL2(errorMsg)
            if errorCode != 1 {
                SweetAlert().showAlert("对不起", subTitle: "\(errorMsg)", style: AlertStyle.Warning)
            }else{
                commonVariable.USERLIST?.userNameLabel?.text = tempUser?.userName!
                commonVariable.LOCAL_USER = tempUser
                self.dismissViewControllerAnimated(true) { () -> Void in
                    
                }
            }
        }
    }
    //点击空白响应
    func handleTapBlank(sender: UITapGestureRecognizer) {
        if sender.state == .Ended {
            self.userTelInsertLable!.resignFirstResponder()
            self.userNameInsertLable!.resignFirstResponder()
            self.userTargetProfsInsertLable!.resignFirstResponder()
            self.userFromSchoolInsertLable!.resignFirstResponder()
        }
        sender.cancelsTouchesInView = false
    }
    func textFieldShouldBeginEditing(textField: UITextField) -> Bool {
        switch textField {
        case self.userTargetProfsInsertLable:
            self.view.endEditing(true)
            showDataPickView()
            return false
            break
        case self.userFromSchoolInsertLable:
            self.view.endEditing(true)
            showCitySelect()
            return false
            break
        default:
            break
        }
        return true
    }
    func textFieldDidEndEditing(textField: UITextField) {
        textField.resignFirstResponder()
    }
    func textFieldShouldReturn(textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        return true
    }
    func pickerDidSelectName(name: String!) {
        self.userFromSchoolInsertLable.text = name
    }
    func cancelBtn() {
        
    }
    //居住地选择
    func showCitySelect(){
        let tempData = UIScreen.mainScreen().bounds.size
        var pickView = AreaPickView.init(frame: CGRectMake(20, tempData.height/2-110, tempData.width - 40, 220))
        pickView.delegate = self
        pickView.show()
    }
    //日期选择
    func showDataPickView(){
        picker = DatePickerView.getShareInstance()
        picker!.textColor = UIColor.redColor()
        picker!.showWithDate(NSDate())
        picker?.block = {
            (date:NSDate)->() in
            let formatter = NSDateFormatter()
            formatter.dateFormat = "yyyy-MM-dd zzz"
            let string = formatter.stringFromDate(date)
            let range:Range = string.rangeOfString(" ")!
            let time = string.substringToIndex(range.endIndex)
            self.userTargetProfsInsertLable!.text = time
        }
        picker?.cancelBlock = {
            ()->() in
            //是的取消的时候置空，而不是“”
            self.userTargetProfsInsertLable!.text = nil
        }
    }
    override func disablesAutomaticKeyboardDismissal() -> Bool {
        return false
    }
}